package cn.kgc.vue.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 张航
 * @Date 2024/7/2
 * @Description JWT工具类
 */
@Component
public class JWTUtil {

    @Value("${jwt.secret}")
   private String secret;
    @Value("${jwt.expireTime}")
    private Integer expireTime;

    private HashMap<String,Object> header;


    public JWTUtil(){
        header = new HashMap<>();
        header.put("alg","HS256");
        header.put("typ","JWT");
    }

    //生成token
    public String createToken(HashMap<String, Object> payload) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DAY_OF_MONTH, expireTime);


        return JWT.create()
                .withHeader(header)
                .withClaim("user",payload)
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(secret));
    }



    //校验token
     public  boolean verify(String token) {
        //当前方法如果没有抛异常 则token校验通过
         JWT.require(Algorithm.HMAC256(secret))
                 .build()
                 .verify(token);


         return true;




     }




    //解析token
    public Map<String,Object> getClaims(String token) {
        Map<String, Object> user = JWT.decode(token).getClaim("user").asMap();

        return user;


    }




}
